#include "napi/native_api.h"
#include <string>
#include <vector>

// 保存从 ETS 传入的回调接口对象引用列表
static std::vector<napi_ref> g_callback_refs;

static void CallCallbackMethodNoArg(napi_env env, const char *methodName)
{
    if (g_callback_refs.empty()) {
        return;
    }
    for (auto &ref : g_callback_refs) {
        if (ref == nullptr) {
            continue;
        }
        napi_value cbObj = nullptr;
        if (napi_get_reference_value(env, ref, &cbObj) != napi_ok || cbObj == nullptr) {
            continue;
        }
        napi_value method = nullptr;
        if (napi_get_named_property(env, cbObj, methodName, &method) != napi_ok) {
            continue;
        }
        napi_valuetype methodType;
        if (napi_typeof(env, method, &methodType) != napi_ok || methodType != napi_function) {
            continue;
        }
        napi_value result;
        napi_call_function(env, cbObj, method, 0, nullptr, &result);
    }
}

static void CallCallbackMethodWithNumber(napi_env env, const char *methodName, double value)
{
    if (g_callback_refs.empty()) {
        return;
    }
    for (auto &ref : g_callback_refs) {
        if (ref == nullptr) {
            continue;
        }
        napi_value cbObj = nullptr;
        if (napi_get_reference_value(env, ref, &cbObj) != napi_ok || cbObj == nullptr) {
            continue;
        }
        napi_value method = nullptr;
        if (napi_get_named_property(env, cbObj, methodName, &method) != napi_ok) {
            continue;
        }
        napi_valuetype methodType;
        if (napi_typeof(env, method, &methodType) != napi_ok || methodType != napi_function) {
            continue;
        }
        // 尽量以整型传递，提升 ArkTS number 解析稳定性（仍为 JS Number）
        napi_value argv[1];
        int32_t iv = static_cast<int32_t>(value);
        if (static_cast<double>(iv) == value) {
            napi_create_int32(env, iv, &argv[0]);
        } else {
            napi_create_double(env, value, &argv[0]);
        }
        napi_value result;
        napi_call_function(env, cbObj, method, 1, argv, &result);
    }
}

static void CallCallbackMethodWithString(napi_env env, const char *methodName, const std::string &value)
{
    if (g_callback_refs.empty()) {
        return;
    }
    for (auto &ref : g_callback_refs) {
        if (ref == nullptr) {
            continue;
        }
        napi_value cbObj = nullptr;
        if (napi_get_reference_value(env, ref, &cbObj) != napi_ok || cbObj == nullptr) {
            continue;
        }
        napi_value method = nullptr;
        if (napi_get_named_property(env, cbObj, methodName, &method) != napi_ok) {
            continue;
        }
        napi_valuetype methodType;
        if (napi_typeof(env, method, &methodType) != napi_ok || methodType != napi_function) {
            continue;
        }
        napi_value argv[1];
        napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &argv[0]);
        napi_value result;
        napi_call_function(env, cbObj, method, 1, argv, &result);
    }
}

static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 + value1, &sum);

    return sum;

}

static napi_value NAPI_Global_setNapiCallback(napi_env env, napi_callback_info info)
{
    size_t argc = 1;
    napi_value args[1] = { nullptr };
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    if (argc < 1 || args[0] == nullptr) {
        napi_value undefinedRet;
        napi_get_undefined(env, &undefinedRet);
        return undefinedRet;
    }

    napi_valuetype valueType;
    napi_typeof(env, args[0], &valueType);
    if (valueType != napi_object) {
        napi_value undefinedRet;
        napi_get_undefined(env, &undefinedRet);
        return undefinedRet;
    }

    // 保存回调对象引用，允许多次注册
    napi_ref ref = nullptr;
    napi_create_reference(env, args[0], 1, &ref);
    if (ref != nullptr) {
        g_callback_refs.push_back(ref);
    }

    napi_value undefinedRet;
    napi_get_undefined(env, &undefinedRet);
    return undefinedRet;
}
static napi_value NAPI_Global_addReturnCallVoid(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value args[2] = { nullptr };
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    double a = 0;
    double b = 0;
    if (argc >= 1 && args[0] != nullptr) {
        napi_get_value_double(env, args[0], &a);
    }
    if (argc >= 2 && args[1] != nullptr) {
        napi_get_value_double(env, args[1], &b);
    }
    double sum = a + b;
    // 触发 void 回调（不带参）
    CallCallbackMethodNoArg(env, "fromNapiCallVoid");
    napi_value ret;
    napi_create_double(env, sum, &ret);
    return ret;
}
static napi_value NAPI_Global_addReturnCallNumber(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value args[2] = { nullptr };
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    double a = 0;
    double b = 0;
    if (argc >= 1 && args[0] != nullptr) {
        napi_get_value_double(env, args[0], &a);
    }
    if (argc >= 2 && args[1] != nullptr) {
        napi_get_value_double(env, args[1], &b);
    }
    double sum = a + b;
    // 触发 number 参数回调
    CallCallbackMethodWithNumber(env, "fromNapiCallWithNumberParam", sum);
    napi_value ret;
    napi_create_double(env, sum, &ret);
    return ret;
}
static napi_value NAPI_Global_addReturnCallString(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value args[2] = { nullptr };
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    double a = 0;
    double b = 0;
    if (argc >= 1 && args[0] != nullptr) {
        napi_get_value_double(env, args[0], &a);
    }
    if (argc >= 2 && args[1] != nullptr) {
        napi_get_value_double(env, args[1], &b);
    }
    double sum = a + b;
    // 如果是整数结果，输出不带小数的字符串
    std::string sumStr;
    int64_t iv = static_cast<int64_t>(sum);
    if (static_cast<double>(iv) == sum) {
        sumStr = std::to_string(iv);
    } else {
        sumStr = std::to_string(sum);
    }
    // 触发 string 参数回调
    CallCallbackMethodWithString(env, "fromNapiCallWithStringParam", sumStr);
    napi_value ret;
    napi_create_double(env, sum, &ret);
    return ret;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"setNapiCallback", nullptr, NAPI_Global_setNapiCallback, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"addReturnCallVoid", nullptr, NAPI_Global_addReturnCallVoid, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"addReturnCallNumber", nullptr, NAPI_Global_addReturnCallNumber, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"addReturnCallString", nullptr, NAPI_Global_addReturnCallString, nullptr, nullptr, nullptr, napi_default, nullptr}
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
